//
//  RefreshControl.swift
//  
//
//  Created by bo wang on 2020/10/2.
//  Copyright © 2020 wangbo. All rights reserved.
//

import Foundation
import MJRefresh

protocol RefreshProtocol: AnyObject {
    func onRefreshing(_ component: MJRefreshComponent, isLoadMore: Bool)
}

class RefreshHeader: MJRefreshNormalHeader {
    override func prepare() {
        super.prepare()
        lastUpdatedTimeLabel?.isHidden = true
        stateLabel?.isHidden = true
    }
}

class RefreshFooter: MJRefreshAutoNormalFooter {
    override func prepare() {
        super.prepare()
        isRefreshingTitleHidden = true
        triggerAutomaticallyRefreshPercent = -5
    }
    
    override func scrollViewContentOffsetDidChange(_ change: [AnyHashable: Any]?) {
        super.scrollViewContentOffsetDidChange(change)
        guard let view = scrollView else { return }
        stateLabel?.isHidden = view.contentSize.height <= view.frame.height
    }
}

extension UIScrollView {
    func enableRefresh(callback: RefreshProtocol? = nil,
                       header headerEnabled: Bool = true,
                       footer footerEnabled: Bool = true) {
        if headerEnabled {
            mj_header = RefreshHeader(refreshingBlock: { [weak self, weak callback] in
                guard let `self` = self, let cb = callback else { return }
                guard let header = self.mj_header else { return }
                cb.onRefreshing(header, isLoadMore: false)
            })
        } else {
            mj_header = nil
        }
        
        if footerEnabled {
            mj_footer = RefreshFooter(refreshingBlock: { [weak self, weak callback] in
                guard let `self` = self, let cb = callback else { return }
                guard let footer = self.mj_footer else { return }
                cb.onRefreshing(footer, isLoadMore: true)
            })
        } else {
            mj_footer = nil
        }
    }
    
    func disableRefreshing() {
        enableRefresh(callback: nil, header: false, footer: false)
    }
    
    func endRefreshing() {
        mj_header?.endRefreshing()
        mj_footer?.resetNoMoreData()
        mj_footer?.endRefreshing()
    }
    
    func noticeNoMoreData() {
        mj_footer?.endRefreshingWithNoMoreData()
    }
    
    var refreshHeader: RefreshHeader? {
        return mj_header as? RefreshHeader
    }
    var refreshFooter: RefreshFooter? {
        return mj_footer as? RefreshFooter
    }
}
